package com.xd.clap.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xd.clap.entity.Admin;
import com.xd.clap.entity.Task;
import com.xd.clap.entity.TaskAllocation;
import com.xd.clap.entity.request.PageParam;
import com.xd.clap.entity.response.AddTask;
import com.xd.clap.entity.response.Result;
import com.xd.clap.entity.response.TaskListVO;
import com.xd.clap.entity.response.TaskVO;
import com.xd.clap.exception.ClapException;
import com.xd.clap.mapper.AdminMapper;
import com.xd.clap.mapper.TaskAllocationMapper;
import com.xd.clap.mapper.TaskMapper;
import com.xd.clap.services.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {


    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TaskAllocationMapper allocationMapper;

    @Resource
    private AdminMapper adminMapper;

    /**
     * 添加任务
     * @param addTask
     * @return
     */
    @Override
    @Transactional
    public Result addTask(AddTask addTask){
        Task task = new Task();
        task.setLocation(addTask.getLocation());
        task.setFullAddress(addTask.getFullAddress());
        task.setContent(addTask.getContent());
        task.setCreateTime(new Date());
        task.setCreateBy(addTask.getCreateBy());
        task.setTaskImg(addTask.getTaskImg());
        task.setTaskStatus("0");
        int insert = taskMapper.insert(task);
        if (insert <= 0) {
            throw new ClapException(100,"上传失败");
        }
        List<TaskAllocation> taskAllocations = addTask.getTaskAllocations();
        if(taskAllocations != null){
            for (TaskAllocation taskAllocation : taskAllocations){
                Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("address", taskAllocation.getProcessedBy()));
                if (admin == null) {
                    throw new ClapException(100,"上传失败");
                }
                TaskAllocation allocation = new TaskAllocation();
                allocation.setTelPhone(admin.getPhone());
                allocation.setProcessedBy(taskAllocation.getProcessedBy());
                allocation.setStatus("0");
                allocation.setTaskId(task.getId());
                int insert1 = allocationMapper.insert(allocation);
                if (insert1 <= 0) {
                    throw new ClapException(100,"上传失败");
                }
            }
        }else {
            throw new ClapException(100,"上传失败");
        }
        return Result.success("1", "上传成功");
    }

    /**
     * 查询任务列表
     * @param pageParam
     * @return
     */
    @Override
    public Result getTask(PageParam pageParam){
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",pageParam.getPhone());
        Admin admin = adminMapper.selectOne(wrapper);
        // 检查admin对象是否为空
        if (admin == null) {
            return Result.fail(100, "加载失败");
        }
        List<TaskListVO> taskVOList = new ArrayList<>();
        if(admin.getAuthority().equals("927360369")){
            QueryWrapper<Task> taskWrapper = new QueryWrapper<>();
            taskWrapper.orderByDesc("create_time");
            if (StringUtils.isNotBlank(pageParam.getKey())){
                taskWrapper.eq("task_status",pageParam.getKey());
            }
            PageHelper.startPage(pageParam.getPage(),pageParam.getPageSize());
            List<Task> taskList = taskMapper.selectList(taskWrapper);
            System.out.println(taskList.getClass());
            for (Task task : taskList) {
                List<TaskAllocation> taskAllocationList = allocationMapper.selectList(new QueryWrapper<TaskAllocation>().eq("task_id", task.getId()));
                int processedCount = 0;
                for (TaskAllocation allocation : taskAllocationList) {
                    if (allocation.getStatus().equals("1")) { // 已处理状态为1
                        processedCount++;
                    }
                }
                int totalCount = taskAllocationList.size();
                TaskListVO taskVO = TaskListVO.of(task, totalCount, processedCount,taskAllocationList);
                taskVOList.add(taskVO);
            }
        }
        PageInfo<TaskListVO> pageInfo = new PageInfo<>(taskVOList);
        if (StringUtils.isNotBlank(pageParam.getKey())) {
            pageInfo.setTotal(taskMapper.selectCount(new QueryWrapper<Task>().eq("task_status",pageParam.getKey())));
        }else {
            pageInfo.setTotal(taskMapper.selectCount(null));
        }
        return Result.success(pageInfo,"加载成功");
    }

    /**
     * 获取任务详情
     * @param id
     * @return
     */
    @Override
    public Result getTaskInfo(Integer id){
        Task task = taskMapper.selectById(id);
        List<TaskAllocation> taskAllocationList = allocationMapper.selectList(new QueryWrapper<TaskAllocation>().eq("task_id", id));
        int processedCount = 0;
        for (TaskAllocation allocation : taskAllocationList) {
               if (allocation.getStatus().equals("1")) { // 已处理状态为1
                processedCount++;
            }
        }
        int totalCount = taskAllocationList.size();
        TaskVO taskVO = new TaskVO();
        taskVO.setLocation(task.getLocation());
        taskVO.setFullAddress(task.getFullAddress());
        taskVO.setContent(task.getContent());
        taskVO.setTaskImg(task.getTaskImg());
        taskVO.setCreateTime(task.getCreateTime());
        taskVO.setCreateBy(task.getCreateBy());
        taskVO.setProcessed(processedCount);
        taskVO.setTotalCount(totalCount);
        taskVO.setTaskAllocations(taskAllocationList);
        return Result.success(taskVO,"加载成功");
    }

    /**
     * app获取任务列表
     * @param pageParam
     * @return
     */
    @Override
    public Result getAppTask(PageParam pageParam){
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",pageParam.getPhone());
        Admin admin = adminMapper.selectOne(wrapper);
        // 检查admin对象是否为空
        if (admin == null) {
            return Result.fail(100, "加载失败");
        }
        List<TaskListVO> taskVOList = new ArrayList<>();
        PageInfo<TaskListVO> pageInfo = null;
        if(admin.getAuthority().equals("927360369")){
            QueryWrapper<Task> taskWrapper = new QueryWrapper<>();
            taskWrapper.orderByDesc("create_time");
            if (StringUtils.isNotBlank(pageParam.getKey())){
                taskWrapper.eq("task_status",pageParam.getKey());
            }
            PageHelper.startPage(pageParam.getPage(), pageParam.getPageSize());
            List<Task> taskList = taskMapper.selectList(taskWrapper);
            for (Task task : taskList) {
                List<TaskAllocation> taskAllocationList = allocationMapper.selectList(new QueryWrapper<TaskAllocation>().eq("task_id", task.getId()));
                int processedCount = 0;
                for (TaskAllocation allocation : taskAllocationList) {
                    if (allocation.getStatus().equals("1")) { // 已处理状态为1
                        processedCount++;
                    }
                }
                int totalCount = taskAllocationList.size();
                TaskListVO taskVO = TaskListVO.of(task, totalCount, processedCount,taskAllocationList);
                taskVOList.add(taskVO);
            }
            pageInfo = new PageInfo<>(taskVOList);
            if (StringUtils.isNotBlank(pageParam.getKey())) {
                pageInfo.setTotal(taskMapper.selectCount(new QueryWrapper<Task>().eq("task_status",pageParam.getKey())));
            }else {
                pageInfo.setTotal(taskMapper.selectCount(null));
            }
        }else {
            QueryWrapper<TaskAllocation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tel_phone",pageParam.getPhone());
            if (StringUtils.isNotBlank(pageParam.getKey())){
                queryWrapper.eq("status",pageParam.getKey());
            }
            List<TaskAllocation> taskAllocationList = allocationMapper.selectList(queryWrapper);
            // 所有任务ID的列表
            List<Integer> taskIds = new ArrayList<>();
            for (TaskAllocation allocation : taskAllocationList) {
                taskIds.add(allocation.getTaskId());
            }

            if (!taskIds.isEmpty()) {
                QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
                taskQueryWrapper.in("id", taskIds);
                taskQueryWrapper.orderByDesc("create_time");
                PageHelper.startPage(pageParam.getPage(),pageParam.getPageSize());
                List<Task> taskList = taskMapper.selectList(taskQueryWrapper);
                for (Task task : taskList) {
                    TaskListVO taskVO = new TaskListVO();
                    taskVO.setId(task.getId());
                    taskVO.setLocation(task.getLocation());
                    taskVO.setFullAddress(task.getFullAddress());
                    taskVO.setContent(task.getContent());
                    taskVO.setTaskImg(task.getTaskImg());
                    taskVO.setCreateTime(task.getCreateTime());
                    taskVO.setCreateBy(task.getCreateBy());
                    taskVOList.add(taskVO);
                }
            }
            pageInfo = new PageInfo<>(taskVOList);
            pageInfo.setTotal(taskAllocationList.size());
        }
        return Result.success(pageInfo,"加载成功");
    }


    @Override
    @Transactional
    public Result updateTask(TaskAllocation taskAllocation) {
        TaskAllocation allocation = allocationMapper.selectOne(new QueryWrapper<TaskAllocation>()
                .eq("tel_phone", taskAllocation.getTelPhone())
                .eq("task_id", taskAllocation.getTaskId()));
        TaskAllocation update = new TaskAllocation();
        update.setId(allocation.getId());
        update.setStatus("1");
        update.setContent(taskAllocation.getContent());
        update.setProcessedImg(taskAllocation.getProcessedImg());
        int i = allocationMapper.updateById(update);
        if (i <= 0) {
            throw new ClapException(100,"上传失败");
        }
        List<TaskAllocation> taskAllocationList = allocationMapper.selectList(new QueryWrapper<TaskAllocation>().eq("task_id", taskAllocation.getTaskId()));
        int processedCount = 0;
        for (TaskAllocation allocations : taskAllocationList) {
            if (allocations.getStatus().equals("1")) { // 已处理状态为1
                processedCount++;
            }
        }
        int totalCount = taskAllocationList.size();
        if(processedCount == totalCount){
            Task task = new Task();
            task.setId(taskAllocation.getTaskId());
            task.setTaskStatus("1");
            int i1 = taskMapper.updateById(task);
            if (i1 <= 0) {
                throw new ClapException(100,"上传失败");
            }
        }
        return Result.success("1", "上传成功");
    }


    /**
     * 删除任务
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteTask(Integer id){
        int i = allocationMapper.delete(new QueryWrapper<TaskAllocation>().eq("task_id", id));
        if (i <= 0) {
            throw new ClapException(100,"删除失败");
        }
        int i1 = taskMapper.deleteById(id);
        if (i1 <= 0) {
            throw new ClapException(100,"删除失败");
        }
        return Result.success("1", "删除成功");
    }
}
